package com.sh.data.engine.influxdb.client;

import com.influxdb.client.InfluxDBClient;
import com.influxdb.client.InfluxDBClientFactory;
import com.influxdb.client.WriteApiBlocking;
import com.influxdb.client.write.Point;
import lombok.extern.slf4j.Slf4j;

import java.time.OffsetDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.List;

/**
 * @author: mengzheng.mhc
 * @date: 2024/3/5 13:50
 */
@Slf4j
public class InfluxDBClientUtil {

    private static final String RFC3339_PATTERN =
        "^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(\\.\\d+)?(Z|[+-]\\d{2}:\\d{2})$";

    public static InfluxDBClient getInfluxDBClient(
        String url, String token, String org, String dbName) {
        // 开启Gzip压缩
        InfluxDBClient influxDBClient =
            InfluxDBClientFactory.create(url, token.toCharArray(), org, dbName);
        influxDBClient.enableGzip();
        return influxDBClient;
    }

    public static void close(InfluxDBClient client) {
        if (client != null) {
            client.close();
        }
    }

    public static void insert(InfluxDBClient client, List<Point> points) {
        WriteApiBlocking writeApi = client.getWriteApiBlocking();
        // Batch write by data points
        writeApi.writePoints(points);
    }

    public static Date convert(Object value) {
        String valueString = value.toString();
        if (valueString.matches(RFC3339_PATTERN)) {
            // 输入的时间戳是RFC 3339格式的字符串
            OffsetDateTime offsetDateTime = OffsetDateTime.parse(valueString, DateTimeFormatter.ISO_OFFSET_DATE_TIME);
            return Date.from(offsetDateTime.toInstant());
        } else if (isLong(valueString)) {
            long date = Long.parseLong(valueString);
            if (valueString.length() == 10) {
                // 输入的时间戳是秒级时间戳
                return new Date(date * 1_000);
            } else if (valueString.length() == 13) {
                // 输入的时间戳是毫秒级时间戳
                return new Date(date);
            } else if (valueString.length() == 16) {
                // 输入的时间戳是微秒级时间戳
                return new Date(date / 1_000);
            } else if (valueString.length() == 19) {
                // 输入的时间戳是纳秒级时间戳
                return new Date(date / 1_000_000);
            }
        }

        throw new IllegalArgumentException("Invalid time format: " + valueString);
    }

    private static boolean isLong(String str) {
        try {
            Long.parseLong(str);
            return true;
        } catch (NumberFormatException e) {
            return false;
        }
    }

    public static void main(String[] args) {
        Date date = InfluxDBClientUtil.convert("2019-10-12T14:20:50.52Z");
        System.out.println("date = " + date);
        date = InfluxDBClientUtil.convert("2019-10-12T14:20:50.52Z");
        System.out.println("date = " + date);
    }
}
